package models

import (
	"gorm.io/gorm"
)

type News struct {
	gorm.Model
	Title    string
	Released string
	Types    string
}

func (n *News) Create() error {
	return DB.Create(&n).Error
}

func (n *News) List(page, pageSize int) (newsList []News, err error) {
	err = DB.Find(&newsList).Scopes(Paginate(page, pageSize)).Error
	return
}
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 5
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

func (n *News) Update() error {
	return DB.Updates(&n).Error
}

func (n *News) GetNewsById() error {
	return DB.Where("id=?", n.ID).Limit(1).Find(&n).Error
}

func (n *News) Del() error {
	return DB.Delete(&n).Error
}
